import { Workspace, createIndexeddbStorage, createMemoryStorage } from '@revesuite/store'
import { emitter, events } from './eventemitter'

import { AffineSchemas } from '@revesuite/blocks/models'
import { IndexeddbPersistence } from 'y-indexeddb'

const REVEZONE_EDITOR_KEY = 'revezone_blocksuite'

class BlocksuiteStorage {
  constructor() {
    if (BlocksuiteStorage.instance) {
      return BlocksuiteStorage.instance
    }
    BlocksuiteStorage.instance = this

    this.initYIndexeddb()
  }
  static instance

  workspace = new Workspace({
    id: REVEZONE_EDITOR_KEY,
    blobStorages: [createIndexeddbStorage, createMemoryStorage]
  }).register(AffineSchemas)

  async initYIndexeddb() {
    const indexeddbPersistence = new IndexeddbPersistence(REVEZONE_EDITOR_KEY, this.workspace.doc)

    this.indexeddbPersistence = indexeddbPersistence

    // @ts-ignore
    window.persistence = indexeddbPersistence

    indexeddbPersistence.on('synced', async () => {
      // console.log('content from the database is loaded');
      emitter.emit(events.WORKSPACE_LOADED)

      // this.workspace.slots.pagesUpdated.on((...args) => {
      //   console.log('--- pagesUpdated ---', ...args);
      // });
    })
  }

  async addPage(pageId) {
    return await this.workspace.createPage({ id: pageId, init: true })
  }

  async deletePage(pageId) {
    try {
      await this.workspace.removePage(pageId)
    } catch (err) {
      console.warn('delete page error: ', err)
    }
  }

  async getAllPageIds() {
    const pageNameList = await this.workspace.getPageNameList()
    const pageIds = pageNameList.map((name) => name.split('space:')?.[1])
    return pageIds
  }
}
export const blocksuiteStorage = new BlocksuiteStorage()
